import axios from 'axios'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: false, // send cookies when cross-domain requests
  timeout: 30000, // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config: { method: string; params: { [x: string]: string } }) => {
    if (
      config.method &&
      config.method.toLowerCase() === 'get' &&
      config.params &&
      Object.keys(config.params).length !== 0
    ) {
      // eslint-disable-next-line prefer-const
      for (let it in config.params) {
        if (typeof config.params[it] === 'undefined') {
          config.params[it] = ''
        }
      }
    }
    return config
  },
  (error: any) => {
    console.log('request:', error) // for debug
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  (response: { data: any }) => {
    const res = response.data
    return res
  },
  (error: any) => {
    console.log('response:' + error) // for debug
    if (error && error.stack.indexOf('timeout') > -1) {
      // 5002 网络超时
      return Promise.reject('5002')
    } else if (error.message.includes('Network')) {
      Message.destroy()
      Message.error({
        message: '无网络,请检查网络',
        showClose: true,
        duration: 2000,
      })
      // 5001 网络错误
      return Promise.reject('5001')
    }
    // 5099 通用错误
    return Promise.reject('5099')
  },
)

export default service
